#!/usr/bin/env python
# coding: utf-8

# In[3]:


'''消元法1'''
import numpy as np

# 线性方程组可表示为AX=b，X=（x，y，z）.T
A = np.array([[3,4,2],[5,3,4],[8,2,7]])
# A为系数矩阵
b =np.array([10, 14, 20])
# b为列向量
a = np.linalg.inv(A) 
# 对A求逆
X = a.dot(b)
# X=a·b

print(X)


# In[4]:


'''消元法2'''
# 直接使用Numpy库中solve函数替代求逆点积运算
import numpy as np

A = np.array([[3,4,2],[5,3,4],[8,2,7]])
# A为系数矩阵
b =np.array([10, 14, 20])
# b为列向量

x = np.linalg.solve(A, b)

print(x)


# In[41]:


'''迭代法'''
import numpy as np
 
# 线性方程组可表示为AX=b，X=（x，y，z）.T
A = np.array([[3,4,2],[5,3,4],[8,2,7]])
# A为系数矩阵
b =np.array([10, 14, 20])
# b为列向量
 
# 迭代法求解方程组的解
B = np.array([[0,-4/3,-2/3],[-5/3,0,-4/3], [-8/7, -2/7, 0]])
M = np.array([[10/3, 14/3, 20/7]])  # 迭代矩阵运算
error = 1.0e-6  
steps = 100    # 允许误差和迭代次数

X = np.array([[6], [0], [-4]]) # 设定X初始值
errorlist = []

for k in range(steps):
  X1 = X
  X = np.matmul(B, X) + M.T
  print('X:\n', X)
  errorlist.append(np.linalg.norm(X-X1))
  if errorlist[-1] < error:
    print('iteration: ', k+1)
    break
 


# In[ ]:




